import type { FC } from 'react';
import dayjs, { type Dayjs } from 'dayjs';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
import { Feather } from '@expo/vector-icons';
import relativeTime from 'dayjs/plugin/relativeTime';
import { useSafeState, useMemoizedFn, useUpdateEffect } from 'ahooks';
import { View, TouchableWithoutFeedback } from 'react-native';
import { primaryColor } from '@/constants/Colors';
import Input from '../Input';
import Picker from './picker';
import styles from './styles';

import type { DateTimeProps } from './types';

dayjs.extend(utc);
dayjs.extend(timezone);
dayjs.extend(relativeTime);

const currentDate = dayjs();

const DateTime: FC<DateTimeProps> = (props) => {
  const { value = currentDate } = props;
  const [show, setShow] = useSafeState(false);
  const [active, setActive] = useSafeState(false);
  const [date, setDate] = useSafeState<Dayjs>(value);

  const resetState = useMemoizedFn(() => {
    if (!value) return;
    if (value !== date) setDate(value);
  });

  const onPressIn = useMemoizedFn(() => {
    setActive(true);
  });

  const onPressOut = useMemoizedFn(() => {
    setActive(false);
  });

  const closePicker = useMemoizedFn(() => {
    setShow(false);
  });

  const openPicker = useMemoizedFn(() => {
    setShow(true);
  });

  const onOk = useMemoizedFn((date: Dayjs) => {
    closePicker();
    props.onChange?.(date);
    if (!props.value) setDate(date);
  });

  useUpdateEffect(resetState, [value]);

  return (
    <>
      <View style={styles.container}>
        <Input
          readOnly
          placeholder="Select date"
          active={active}
          value={date.format('MM/DD/YYYY')}
          prefix={focus => {
            return (
              <Feather
                size={18}
                name="calendar"
                color={focus ? primaryColor : "#aaa"}
              />
            );
          }}
        />
        <TouchableWithoutFeedback
          disabled={props.disabled}
          onPress={openPicker}
          onPressIn={onPressIn}
          onPressOut={onPressOut}
        >
          <View style={styles.btn} />
        </TouchableWithoutFeedback>
      </View>
      <Picker
        show={show}
        onOk={onOk}
        value={date}
        onCancel={closePicker}
      />
    </>
  );
}

export default DateTime;